// src/utils/request.ts
import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { BASE_API } from '../config/index'
import router from '@/router'

type AxiosRequestConfig = axios.AxiosRequestConfig
type AxiosResponse<T = any> = axios.AxiosResponse<T>

// =======================
// Loading 管理
// =======================
let loadingInstance: ReturnType<typeof ElLoading.service> | null = null
let loadingCount = 0

function showLoading() {
  if (loadingCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  loadingCount++
}

function hideLoading() {
  loadingCount--
  if (loadingCount <= 0 && loadingInstance) {
    setTimeout(() => {
      if (loadingCount <= 0) {
        loadingInstance?.close()
        loadingInstance = null
      }
    }, 300)
    loadingCount = 0 // 防止负数
  }
}

// =======================
// 创建 axios 实例
// =======================
const service = axios.create({
  baseURL: BASE_API,
  timeout: 1000 * 100, // 100秒超时
  validateStatus: (status) => status >= 200 && status < 500 // 不因状态码 reject
})

// =======================
// 请求拦截器
// =======================
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
      try {
        const data = JSON.parse(token)
        const tokenStr = data.token
        if (tokenStr) {
          config.headers.token = tokenStr
        }
      } catch (e) {
        console.warn('Token 解析失败', e)
      }
    }

    // 可选：某些请求不显示 loading
    // if (config.headers['X-No-Loading'] !== 'true') {
    //   showLoading()
    // }

    return config
  },
  (error) => {
    hideLoading()
    return Promise.reject(error)
  }
)

// =======================
// 响应拦截器（统一处理）
// =======================
service.interceptors.response.use(
  (response: AxiosResponse) => {
    hideLoading()
    const res = response.data
    const skipCodeCheck = response.config.headers['X-Skip-Code-Check'] === 'true'

    if (skipCodeCheck) {
      return res
    }

    const successCodes = [200,0, '200','0']
    if (!successCodes.includes(res.code)) {
      const errorMsg = res.message || res.msg || '操作失败'
      ElMessage({
        message: errorMsg,
        type: 'error',
        duration: 3000
      })

      // 401 处理
      if (res.code === 401 || response.status === 401) {
        localStorage.removeItem('token')
        sessionStorage.removeItem('token')
        router.push("/login").catch(err => console.error("路由跳转失败", err))
      }

      return Promise.reject(new Error(errorMsg))
    }

    // ✅ 请求成功：返回 res.data（业务数据）
    return res.data
  },
  (error) => {
    hideLoading()

    const message =
      error.response?.data?.message ||
      error.response?.data?.msg ||
      error.message ||
      '网络异常'

    // 401 处理
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      sessionStorage.removeItem('token')
      ElMessage({
        message: '登录已失效，请重新登录',
        type: 'warning',
        duration: 3000
      })
      router.push("/login").catch(err => console.error("跳转登录失败", err))
    } else {
      // 非 401 错误才提示
      ElMessage({
        message: message,
        type: 'error',
        duration: 3000
      })
    }

    return Promise.reject(error)
  }
)

export default service
